import {
  Badge,
  Button,
  Card,
  Col,
  DatePicker,
  Divider,
  Dropdown,
  Form,
  Icon,
  Input,
  InputNumber,
  Menu,
  Row,
  Select,
  message,
  Popconfirm,
} from 'antd';
import React, { Component, Fragment } from 'react';

import { Dispatch } from 'redux';
import { FormComponentProps } from 'antd/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { SorterResult } from 'antd/es/table';
import { connect } from 'dva';
import moment from 'moment';
import { StateType } from './model';
import CreateForm from './components/CreateForm';
import StandardTable, { StandardTableColumnProps } from './components/StandardTable';
import UpdateForm, { FormValsType } from './components/UpdateForm';
import { TableListItem, TableListPagination, TableListParams } from './data.d';

import styles from './style.less';
import { bindEnterprises } from '@/pages/manage/enterprise/joinEnterprise/service';

const R = require('ramda');
const FormItem = Form.Item;
const { Option } = Select;
const getValue = (obj: { [x: string]: string[] }) =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  manageEnterpriseJoinEnterprise: StateType;
}

interface TableListState {
  expandForm: boolean;
  selectedRows: TableListItem[];
  formValues: { [key: string]: string };
}

/* eslint react/no-multi-comp:0 */
@connect(
  ({
    manageEnterpriseJoinEnterprise,
    loading,
    global,
  }: {
    manageEnterpriseJoinEnterprise: StateType;
    global: StateType;
    loading: {
      models: {
        [key: string]: boolean;
      };
    };
  }) => ({
    manageEnterpriseJoinEnterprise,
    global,
    loading: loading.models.manageEnterpriseJoinEnterprise,
  }),
)
class TableList extends Component<TableListProps, TableListState> {
  state: TableListState = {
    expandForm: false,
    selectedRows: [],
    formValues: {},
  };

  columns: StandardTableColumnProps[] = [
    {
      title: '企业名称',
      dataIndex: 'companyname',
    },
    {
      title: '移动电话',
      dataIndex: 'mobile',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <Popconfirm
            placement="leftTop"
            onConfirm={this.handleUpdate.bind(this, record)}
            okText="是"
            cancelText="否"
            title={'是否确认加入该企业'}
          >
            <a href="#">申请加入</a>
          </Popconfirm>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch, form, global } = this.props;
    const { userInfo } = global;

    dispatch({
      type: 'manageEnterpriseJoinEnterprise/refreshState',
      payload: {
        data: {
          list: [],
          pagination: {},
        },
      },
    });


    if(!R.isEmpty(userInfo) && !R.isNil(userInfo) && !R.equals(userInfo)('{}')) {
      message.info('你已经有企业归属,暂无法进行绑定');
    }
  }

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
  };

  handleSelectRows = (rows: TableListItem[]) => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const { dispatch, form, global } = this.props;
    const { userInfo } = global;

    if(!R.isEmpty(userInfo) && !R.isNil(userInfo) && !R.equals(userInfo)('{}')) {
      message.info('你已经有企业归属,暂无法进行绑定');
      return;
    }

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        nameOrCode: fieldsValue.nameOrCode,
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'manageEnterpriseJoinEnterprise/getEnterprises',
        payload: values,
      });
    });
  };

  handleUpdate = record => {
    const { dispatch, global } = this.props;
    const { userInfo } = global;
    let values = {};
    values.cstId = record.id;
    dispatch({
      type: 'manageEnterpriseJoinEnterprise/bindEnterprises',
      payload: {
        ...values,
        onFail: () => {
          this.props.dispatch({
            type: 'manageEnterpriseJoinEnterprise/getEnterprises',
          });
        },
      },
    });
  };

  renderSimpleForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="企业名称">
              {getFieldDecorator('nameOrCode', {
                rules: [
                  {
                    required: true,
                    message: '请输入企业名称查询',
                  },
                ],
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      manageEnterpriseJoinEnterprise: { data },
      loading,
    } = this.props;


    const { selectedRows } = this.state;

    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}></div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
